package com.enjoy.mvc;

import com.enjoy.mvc.service.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.Queue;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;

@RestController
public class HelloController {

    public Queue<DeferredResult<Object>> queue = new ConcurrentLinkedQueue<>();

    @Autowired
    private A a;
    @RequestMapping("/c")
    public String c() {
        System.out.println("hello,tomcat");
        System.out.println(a);
        return "hello,tomcat";
    }

    // 异步处理，基于Callable
    @RequestMapping("order")
    public Callable<String> order() {

        // 申明Callable完成异步
        Callable<String> callable = () -> {
            System.out.println("子线程:" + Thread.currentThread());

            Thread.sleep(1000);

            return "order successful";
        };

        System.out.println("主线程:" + Thread.currentThread());
        return callable;
    }


    // 异步处理，基于DeferredResult
    @RequestMapping("createOrder")
    public DeferredResult<Object> createOrder() {
        DeferredResult<Object> deferredResult = new DeferredResult<>((long) 3000, "create fail");
        queue.offer(deferredResult);
        return deferredResult;
    }

    @RequestMapping("create")
    public String create() {
        // 创建订单
        String id = UUID.randomUUID().toString();
        DeferredResult<Object> deferredResult = queue.poll();
        assert deferredResult != null;
        deferredResult.setResult(id);
        return "create success, orderId =" + id;
    }

}
